package com.qingcloud.adminbackend.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class CommonUtil {
    public static final String DATAFORMAT = "yyyy-MM-dd";
    public static final String DATAFORMAT_YEAR = "yyyy";
    public static final String DATAFORMAT_MONTH = "yyyy-MM";
    public static final String DATAFORMAT_HH = "yyyy-MM-dd HH";
    public static final String DATAFORMAT_MM = "yyyy-MM-dd HH:mm";
    public static final String DATAFORMAT_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String DATAFORMAT_HM = "HH:mm";

    public CommonUtil() {
    }

    public static boolean isEmpty(Object object) {
        boolean isEmpty = false;
        if (object != null && !"".equals(object)) {
            if (object instanceof Collection) {
                Collection<?> collection = (Collection) object;
                isEmpty = collection.isEmpty();
            } else if (object instanceof Map) {
                Map<?, ?> map = (Map) object;
                isEmpty = map.isEmpty();
            } else if (object.getClass().isArray()) {
                Object[] objects = (Object[]) ((Object[]) object);
                isEmpty = objects.length <= 0;
            }
        } else {
            isEmpty = true;
        }

        return isEmpty;
    }

    public static String convertObjToStr(Object object) {
        return isNotEmpty(object) ? object.toString().trim() : "";
    }

    public static String convertObjDateToStr(Object objdate, String fmt) {
        if (isNotEmpty(objdate)) {
            String val = String.valueOf(objdate).trim();
            if ("".equals(val)) {
                return "";
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat sd = new SimpleDateFormat(fmt);
                Date st = null;

                try {
                    st = sdf.parse(val);
                    return sd.format(st);
                } catch (ParseException var7) {
                    var7.printStackTrace();
                    return "";
                }
            }
        } else {
            return "";
        }
    }

/*    public static Date convertObjDate(Object objdate) {
        return objdate == null?null:(StringUtils.isBlank(objdate.toString())?null:DateUtil.parse(objdate.toString()));
    }*/

    public static Integer convertObjToInteger(Object object) {
        if (isNotEmpty(object)) {
            String val = String.valueOf(object).trim();
            return "".equals(val) ? Integer.valueOf(0) : Integer.valueOf(Integer.parseInt(val));
        } else {
            return Integer.valueOf(0);
        }
    }

    public static Float convertObjToFloat(Object object) {
        if (isNotEmpty(object)) {
            String val = String.valueOf(object).trim();
            return "".equals(val) ? Float.valueOf(0.0F) : Float.valueOf(Float.parseFloat(val));
        } else {
            return Float.valueOf(0.0F);
        }
    }

    public static Double convertObjToDouble(Object object) {
        if (isNotEmpty(object)) {
            String val = String.valueOf(object).trim();
            return "".equals(val) ? Double.valueOf(0.0D) : Double.valueOf(Double.parseDouble(val));
        } else {
            return Double.valueOf(0.0D);
        }
    }

    public static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

    public static Map<String, String> getParameters(HttpServletRequest request) {
        Map<String, String> map = new HashMap();
        Enumeration e = request.getParameterNames();

        while (true) {
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String[] list = request.getParameterValues(key);
                if (list.length == 1) {
                    map.put(key, list[0]);
                } else if (list.length > 1) {
                    String value = null;

                    for (int i = 0; i < list.length; ++i) {
                        if (i == 0) {
                            value = list[i];
                        } else {
                            value = value + ',' + list[i];
                        }
                    }

                    map.put(key, value);
                }
            }

            return map;
        }
    }

    public static String stringArrayToStrin(String[] str) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < str.length; ++i) {
            sb.append("'").append(str[i]).append("'").append(",");
        }

        return sb.toString().substring(0, sb.length() - 1);
    }

    public static Boolean checkList(List<?> list) {
        return list != null && list.size() > 0 ? Boolean.valueOf(true) : Boolean.valueOf(false);
    }

    public static String getInSqlByIds(String[] postIds) {
        String ids = "";

        for (int i = 0; i < postIds.length; ++i) {
            ids = ids + postIds[i];
            if (i < postIds.length - 1) {
                ids = ids + ",";
            }
        }

        return ids;
    }

//    public static Integer getIntValue(Object obj) {
//        Integer intValue = Integer.valueOf(0);
//        if(obj != null) {
//            if(obj instanceof BigDecimal) {
//                intValue = Integer.valueOf(((BigDecimal)obj).intValue());
//            } else if(obj instanceof Integer) {
//                intValue = Integer.valueOf(((Integer)obj).intValue());
//            } else if(obj instanceof Float) {
//                intValue = Integer.valueOf(((Float)obj).intValue());
//            } else if(obj instanceof Double) {
//                intValue = Integer.valueOf(((Double)obj).intValue());
//            } else if(obj instanceof Long) {
//                intValue = Integer.valueOf(((Long)obj).intValue());
//            } else if(obj instanceof String) {
//                boolean isN = StringUtils.isNumeric(obj.toString());
//                if(isN) {
//                    intValue = Integer.valueOf(Integer.parseInt(obj.toString()));
//                }
//            } else if(obj instanceof Byte) {
//                intValue = Integer.valueOf(((Byte)obj).intValue());
//            } else if(obj instanceof Short) {
//                intValue = Integer.valueOf(((Short)obj).intValue());
//            }
//        }
//
//        return intValue;
//    }

    public static Float getFloatValue(Object obj) {
        Float floatValue = Float.valueOf(0.0F);
        if (obj != null) {
            BigDecimal b;
            if (obj instanceof Float) {
                floatValue = (Float) obj;
                b = new BigDecimal((double) floatValue.floatValue());
                float f = b.setScale(1, 4).floatValue();
                return Float.valueOf(f);
            } else if (obj instanceof BigDecimal) {
                b = (BigDecimal) obj;
                floatValue = Float.valueOf(b.setScale(1, 4).floatValue());
                return floatValue;
            } else if (obj instanceof Integer) {
                floatValue = Float.valueOf(((Integer) obj).floatValue());
                b = new BigDecimal((double) floatValue.floatValue());
                return Float.valueOf(b.setScale(2, 4).floatValue());
            } else if (obj instanceof Double) {
                floatValue = Float.valueOf(((Double) obj).floatValue());
                b = new BigDecimal((double) floatValue.floatValue());
                return Float.valueOf(b.setScale(2, 4).floatValue());
            } else if (obj instanceof String) {
                floatValue = Float.valueOf(obj.toString());
                b = new BigDecimal((double) floatValue.floatValue());
                return Float.valueOf(b.setScale(2, 4).floatValue());
            } else {
                b = new BigDecimal(0);
                return Float.valueOf(b.setScale(2, 4).floatValue());
            }
        } else {
            return floatValue;
        }
    }

//    public static Integer getIntValueDefaultZero(Object obj) {
//        Integer intValue = Integer.valueOf(0);
//        if(obj != null) {
//            if(obj instanceof BigDecimal) {
//                intValue = Integer.valueOf(((BigDecimal)obj).intValue());
//            } else if(obj instanceof Integer) {
//                intValue = Integer.valueOf(((Integer)obj).intValue());
//            } else if(obj instanceof Float) {
//                intValue = Integer.valueOf(((Float)obj).intValue());
//            } else if(obj instanceof Double) {
//                intValue = Integer.valueOf(((Double)obj).intValue());
//            } else if(obj instanceof Long) {
//                intValue = Integer.valueOf(((Long)obj).intValue());
//            } else if(obj instanceof String) {
//                boolean isN = StringUtils.isNumeric(obj.toString());
//                if(isN) {
//                    intValue = Integer.valueOf(Integer.parseInt(obj.toString()));
//                }
//            } else if(obj instanceof Byte) {
//                intValue = Integer.valueOf(((Byte)obj).intValue());
//            } else {
//                intValue = Integer.valueOf(((Short)obj).intValue());
//            }
//        }
//
//        if(intValue.intValue() < 0) {
//            intValue = Integer.valueOf(0);
//        }
//
//        return intValue;
//    }

    public static Float getFloatValueDefaultZero(Object obj) {
        Float floatValue = Float.valueOf(0.0F);
        if (obj != null) {
            BigDecimal b;
            if (obj instanceof Float) {
                floatValue = (Float) obj;
                b = new BigDecimal((double) floatValue.floatValue());
                float f = b.setScale(1, 4).floatValue();
                return Float.valueOf(f);
            } else if (obj instanceof BigDecimal) {
                b = (BigDecimal) obj;
                floatValue = Float.valueOf(b.setScale(1, 4).floatValue());
                return floatValue;
            } else if (obj instanceof Integer) {
                floatValue = Float.valueOf(((Integer) obj).floatValue());
                b = new BigDecimal((double) floatValue.floatValue());
                return Float.valueOf(b.setScale(2, 4).floatValue());
            } else if (obj instanceof Double) {
                floatValue = Float.valueOf(((Double) obj).floatValue());
                b = new BigDecimal((double) floatValue.floatValue());
                return Float.valueOf(b.setScale(2, 4).floatValue());
            } else {
                floatValue = Float.valueOf(((Short) obj).floatValue());
                b = new BigDecimal((double) floatValue.floatValue());
                return Float.valueOf(b.setScale(2, 4).floatValue());
            }
        } else {
            if (floatValue.floatValue() < 0.0F) {
                floatValue = Float.valueOf(0.0F);
            }

            return floatValue;
        }
    }

    public static BigDecimal str2BigDecimal(String str) {
        return str != null && !"".equals(str) ? new BigDecimal(str) : new BigDecimal(0);
    }

    public static BigDecimal str2BdPoint6(String str) {
        if (str != null && !"".equals(str)) {
            BigDecimal b = new BigDecimal(str);
            b.setScale(6, 4);
            return b;
        } else {
            return new BigDecimal(0);
        }
    }

    public static Double bigDecimal2Double(BigDecimal decimal) {
        return decimal != null ? Double.valueOf(decimal.doubleValue()) : null;
    }

    public static BigDecimal obj2Decimal(Object obj) {
        return obj != null ? (obj instanceof BigDecimal ? (BigDecimal) obj : str2BigDecimal(obj.toString())) : null;
    }

    public static boolean hasSameObject(List<? extends Object> list, List<? extends Object> list2) {
        List totalList = new ArrayList();
        totalList.addAll(list);
        totalList.addAll(list2);
        return totalList.size() != (new HashSet(totalList)).size();
    }

    public static Object formartNum(Object value, int d) {
        if (null != value && !StringUtils.isEmpty((value.toString()))) {
            BigDecimal bd = new BigDecimal(value.toString());
            bd = bd.setScale(d, RoundingMode.HALF_UP);
            return bd.toString();
        } else {
            return value;
        }
    }

    /**
     * 通过风向名称获取风向度数
     *
     * @param
     * @return
     */
    public static String getWindDirectionValue(float windAngel) {
        String windDirection = "";
        if (windAngel == 0) {
            windDirection = "正北风";
        } else if (windAngel > 0 && windAngel < 90) {
            windDirection = "东北风";
        } else if (windAngel == 90) {
            windDirection = "正东风";
        } else if (windAngel > 90 && windAngel < 180) {
            windDirection = "东南风";
        } else if (windAngel == 180) {
            windDirection = "正南风";
        } else if (windAngel > 180 && windAngel < 270) {
            windDirection = "西南风";
        } else if (windAngel == 270) {
            windDirection = "正西风";
        } else if (windAngel > 270 && windAngel < 360) {
            windDirection = "西北风";
        } else if (windAngel == 360) {
            windDirection = "正北风";
        } else if (windAngel > 360) {
            windDirection = "无持续风向";
        } else {
            windDirection = "--";
        }
        return windDirection;
    }

    /**
     * 通过风速值获取对应的风力
     *
     * @param
     * @return
     */
    public static String getwindPowerByValue(float windPowerValue) {
        if (windPowerValue >= 0.0 && windPowerValue <= 0.2)
            return "无风";
        else if (windPowerValue >= 0.3 && windPowerValue <= 1.5)
            return "软风";
        else if (windPowerValue >= 1.6 && windPowerValue <= 3.3)
            return "轻风";
        else if (windPowerValue >= 3.4 && windPowerValue <= 5.4)
            return "微风";
        else if (windPowerValue >= 5.5 && windPowerValue <= 7.9)
            return "和风";
        else if (windPowerValue >= 8.0 && windPowerValue <= 10.7)
            return "劲风";
        else if (windPowerValue >= 10.8 && windPowerValue <= 13.8)
            return "强风";
        else if (windPowerValue >= 13.9 && windPowerValue <= 17.1)
            return "疾风";
        else if (windPowerValue >= 17.2 && windPowerValue <= 20.7)
            return "大风";
        else if (windPowerValue >= 20.8 && windPowerValue <= 24.4)
            return "烈风";
        else if (windPowerValue >= 24.5 && windPowerValue <= 28.4)
            return "狂风";
        else if (windPowerValue >= 28.5 && windPowerValue <= 32.6)
            return "暴风";
        else
            return "飓风";
    }

    /**
     * 判断字符是否为数字
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 小数取整
     *
     * @param s
     * @return
     */
    public static int ObjectToInt(String s) {
        if (s.indexOf(".") > 0) {
            //正则表达
            s = s.replaceAll("0+?$", "");//去掉后面无用的零
            s = s.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
        }
        int num = Integer.valueOf(s);
        return num;
    }


    public static Boolean isSameList(List<String> list1, List<String> list2) {
        if (list1.size() != list2.size()) {
            return false;
        }
        for (String object : list1) {
            if (!list2.contains(object)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 去重集合
     *
     * @param src
     * @param oth
     * @return
     */
    public static List removeAll(List src, List oth) {
        LinkedList result = new LinkedList(src);//大集合用linkedlist
        HashSet othHash = new HashSet(oth);//小集合用hashset
        Iterator iter = result.iterator();//采用Iterator迭代器进行数据的操作
        while (iter.hasNext()) {
            if (othHash.contains(iter.next())) {
                iter.remove();
            }
        }
        return result;
    }

    /**
     * 集合交集
     *
     * @param src
     * @param oth
     * @return
     */
    public static List intersection(List src, List oth) {
        LinkedList linked = new LinkedList(src);
        LinkedList result = new LinkedList(src);//大集合用linkedlist
        HashSet othHash = new HashSet(oth);//小集合用hashset
        Iterator iter = result.iterator();//采用Iterator迭代器进行数据的操作
        while (iter.hasNext()) {
            if (othHash.contains(iter.next())) {
                linked.add(iter.next());
            }
        }
        return linked;
    }

    /**
     * 取集合的合集
     *
     * @param src
     * @param oth
     * @return
     */
    public static Set intersectionAll(List oth, List oth2) {
        Set set = new HashSet();
        oth.stream().forEach(it -> {
            set.add(it);
        });
        oth2.stream().forEach(it -> {
            set.add(it);
        });
        return set;
    }

    /**
     * 希尔排序
     *
     * @param list
     */
    public static Integer[] shellSort(List<String> list) {
        List<Integer> sfids = new ArrayList<>();
        for (String sensorFactor : list) {
            sfids.add(Integer.valueOf(sensorFactor));
        }
        Integer[] a = new Integer[sfids.size()];
        sfids.toArray(a);
        double gap = a.length;//增量长度
        int dk, sentinel, k;
        while (true) {
            gap = (int) Math.ceil(gap / 2);//逐渐减小增量长度
            dk = (int) gap;//确定增量长度
            for (int i = 0; i < dk; i++) {
                //用增量将序列分割，分别进行直接插入排序。随着增量变小为1，最后整体进行直接插入排序
                for (int j = i + dk; j < a.length; j = j + dk) {
                    k = j - dk;
                    sentinel = a[j];
                    while (k >= 0 && sentinel < a[k]) {
                        a[k + dk] = a[k];
                        k = k - dk;
                    }
                    a[k + dk] = sentinel;
                }
            }
            //当dk为1的时候，整体进行直接插入排序
            if (dk == 1) {
                break;
            }
        }
        return a;
    }

    /**
     * 希尔排序
     *
     * @param list
     */
    public static List shellSortASC(List<String> list) {
        Integer[] a = shellSort(list);
        return Arrays.asList(a);
    }

    /**
     * 希尔排序
     *
     * @param list
     */
    public static List shellSortDESC(List<String> list) {
        Integer[] a = shellSort(list);
        for (int i = 0; i < a.length/2; i++) {
            int t;
            t=a[i];
            a[i]=a[a.length-1-i];
            a[a.length-1-i]=t;
        }
        return Arrays.asList(a);
    }

    /**
     * 正则验证数字字母
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        String regex = "^[^\u4e00-\u9fa5]+$";
        return str.matches(regex);
    }
}
